// 检查版本
export function checkVersion(versionData) {
  return new Promise((resolve, reject) => {
    plus.runtime.getProperty(plus.runtime.appid, function(inf) {
      resolve(parseInt(inf.versionCode) < parseInt(versionData.version))
    })
  })
}

// 下载新版本
export function doUpdateVersion(url, type, callback) {
  const downloadTask = uni.downloadFile({// 执行下载
    url, // 下载地址
    success: downloadResult => { // 下载成功
      const path = downloadResult.tempFilePath
      if (type === 0 || type === 2) plus.runtime.install(path)
      else {
        plus.runtime.install(path, {
          force: true
        }, () => {
          plus.runtime.restart()
        })
      }
    }
  })

  downloadTask.onProgressUpdate((res) => {
    if (callback) callback(res.progress)
  })
}

// 打开子窗体
export function openSubView(path, animationType, zIndex = 11, maskId, maskZIndex = 10) {
  function getRuntime() {
    return typeof window === 'object' && typeof navigator === 'object' && typeof document === 'object' ? 'webview' : 'v8'
  }

  function getPageId() {
    return plus.webview.currentWebview().id
  }
  const defaultStyle = {
    top: 0,
    bottom: 0,
    left: 0,
    right: 0,
    usingComponents: {},
    animationType,
    animationDuration: 300,
    zIndex,
    backButtonAutoControl: 'close',
    background: 'rgba(0,0,0,0)',
    uniNView: {
      path,
      defaultFontSize: plus.screen.resolutionWidth / 20,
      viewport: plus.screen.resolutionWidth
    }
  }
  const maskStyle = {
    top: 0,
    bottom: 0,
    left: 0,
    right: 0,
    usingComponents: {},
    animationType: 'fade-in',
    animationDuration: 300,
    maskZIndex,
    backButtonAutoControl: 'close',
    background: 'rgba(0,0,0,0)',
    uniNView: {
      path: '/components/mask-nvue/mask-nvue',
      defaultFontSize: plus.screen.resolutionWidth / 20,
      viewport: plus.screen.resolutionWidth
    }
  }
  const pageId = `page${Date.now()}`
  const page = plus.webview.create('', pageId, defaultStyle, {
    extras: {
      from: getPageId(),
      runtime: getRuntime()
    }
  })
  const mask = plus.webview.create('', maskId, maskStyle, {
    extras: {
      from: getPageId(),
      runtime: getRuntime()
    }
  })
  mask.show(maskStyle.animationType, maskStyle.animationDuration)
  page.show(defaultStyle.animationType, defaultStyle.animationDuration)
}
